﻿using MIO.Client.Protocal;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MIO.Client.Handler
{
    public class ReceiveHandler
    {
        private Thread thReceive = null;
        private bool isStopped = false;
        private IOClient client;
        private ConcurrentQueue<Packet> packetQueue = null;
        private PacketHandler packetHandler;

        public  ReceiveHandler(IOClient client, ConcurrentQueue<Packet> packetQueue,PacketHandler packetHandler)
        {
            this.client = client;
            this.packetQueue = packetQueue;
            this.packetHandler = packetHandler;
        }

        public void start()
        {
            isStopped = false;
            if (thReceive != null)
                stop();
            thReceive = new Thread(handler);
            thReceive.IsBackground = true;
            thReceive.Start();
        }

        private void handler()
        {
            Packet packet = null;
            while (!isStopped)
            {
                
                if (packetQueue.TryDequeue(out packet))
                {
                    Task.Factory.StartNew(()=> {
                        packetHandler.handler(packet);
                    });
                }
            }
        }

        public void stop()
        {
            isStopped = true;
            if (thReceive != null)
            {
                try
                {
                    while (thReceive.IsAlive) { }
                    thReceive.Abort();
                    thReceive = null;
                }
                catch { }
            }
            Packet discardPacket = null;
            while (packetQueue.Count > 0)
            {
                packetQueue.TryDequeue(out discardPacket);
            }
        }
    }
}
